import re
import logging
from typing import Dict, List, Tuple, Optional

class ReviewValidator:
    """综述内容验证器"""
    
    def __init__(self, min_citations: int = 5):
        self.min_citations = min_citations
        self.logger = logging.getLogger(__name__)

    def validate_review(self, content: str, citations: List[Dict]) -> Tuple[bool, str]:
        """增强的验证逻辑"""
        try:
            self.logger.debug("开始验证综述内容...")
            
            if not content or not citations:
                return False, "内容或引用为空"

            # 引用格式验证
            citation_marks = re.findall(r'<sup>(\d+)</sup>', content)
            self.logger.debug(f"发现引用标记: {citation_marks}")
            
            if not citation_marks:
                return False, "未找到引用标记"

            # 引用编号验证
            used_numbers = set(map(int, citation_marks))
            valid_numbers = {c['number'] for c in citations}
            
            self.logger.debug(f"使用的引用编号: {sorted(used_numbers)}")
            self.logger.debug(f"有效的引用编号: {sorted(valid_numbers)}")
            
            if not used_numbers.issubset(valid_numbers):
                invalid_cites = used_numbers - valid_numbers
                return False, f"存在无效引用编号: {invalid_cites}"

            # 引用密度验证
            paragraphs = [p for p in content.split('\n\n') 
                         if p.strip() and not p.startswith('#')]
            
            uncited_paras = [i for i, p in enumerate(paragraphs, 1)
                            if len(p) > 100 and not re.search(r'<sup>', p)]
            
            if uncited_paras:
                return False, f"段落 {uncited_paras} 缺少引用"

            return True, "验证通过"

        except Exception as e:
            self.logger.error(f"验证过程异常: {str(e)}")
            return False, str(e)

    def _validate_structure(self, content: str) -> bool:
        """验证文档结构"""
        required_sections = ['Abstract', 'Introduction', 'References']
        content_lower = content.lower()
        
        return all(section.lower() in content_lower for section in required_sections)

    def _validate_citations(self, content: str, citations: List[Dict]) -> bool:
        """验证引用格式和一致性"""
        try:
            # 检查引用标记格式
            citation_marks = re.findall(r'<sup>(\d+)</sup>', content)
            if not citation_marks:
                return False

            # 检查参考文献格式
            ref_pattern = r'\[(\d+)\]\s(.+?),\s(.+?),\s(\d{4})'
            refs = re.findall(ref_pattern, content)
            
            # 验证编号一致性
            used_numbers = set(map(int, citation_marks))
            ref_numbers = {int(num) for num, *_ in refs}
            
            return used_numbers == ref_numbers

        except Exception as e:
            self.logger.error(f"引用验证失败: {str(e)}")
            return False

    def get_citation_stats(self, content: str) -> Dict:
        """获取引用统计信息"""
        try:
            citations = re.findall(r'<sup>(\d+)</sup>', content)
            paragraphs = [p.strip() for p in content.split('\n\n') if p.strip()]
            
            return {
                'total_citations': len(citations),
                'unique_citations': len(set(citations)),
                'paragraphs_with_citations': sum(1 for p in paragraphs 
                                               if '<sup>' in p),
                'total_paragraphs': len(paragraphs),
                'citation_density': len(citations) / len(paragraphs) if paragraphs else 0
            }
        except Exception as e:
            self.logger.error(f"统计计算失败: {str(e)}")
            return {}
